// API服务类，用于与后端通信
// const API_BASE_URL = "http://draw-guess.bdow.com.cn:3001";
const API_BASE_URL = "";

export interface WordBank {
  id: string;
  name: string;
  wordCount: number;
  isDefault: boolean;
  createdAt: string;
}

export interface WordBankDetail {
  id: string;
  name: string;
  words: string[];
  isDefault: boolean;
  createdAt: string;
}

export class ApiService {
  private baseUrl: string;

  constructor(baseUrl: string = API_BASE_URL) {
    this.baseUrl = baseUrl;
  }

  // 获取所有题库
  async getWordBanks(): Promise<WordBank[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/wordbanks`);
      if (!response.ok) {
        throw new Error("获取题库列表失败");
      }
      return await response.json();
    } catch (error) {
      console.error("获取题库列表错误:", error);
      throw error;
    }
  }

  // 获取特定题库详情
  async getWordBank(id: string): Promise<WordBankDetail> {
    try {
      const response = await fetch(`${this.baseUrl}/api/wordbanks/${id}`);
      if (!response.ok) {
        throw new Error("获取题库详情失败");
      }
      return await response.json();
    } catch (error) {
      console.error("获取题库详情错误:", error);
      throw error;
    }
  }

  // 创建自定义题库
  async createWordBank(name: string, words: string[]): Promise<WordBankDetail> {
    try {
      const response = await fetch(`${this.baseUrl}/api/wordbanks`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ name, words }),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "创建题库失败");
      }

      return await response.json();
    } catch (error) {
      console.error("创建题库错误:", error);
      throw error;
    }
  }

  // 检查服务器状态
  async getServerStatus() {
    const res = await fetch(`/api/health`);
    if (!res.ok) throw new Error("服务器连接失败");
    return res.json();
  }
}

// 单例模式
export const apiService = new ApiService();
